﻿$(document).ready(function() {
    $("#loginBtn").click(function() {
        if (validateInput()) {
            $("#loginBtn").button('loading').css({ 'background': '#6a7b42' });
            authorizeUser($('#loginBox').val(), $('#passwordBox').val());
        }
    });
});

function validateInput() {
    $('#servErrorTxt').hide();
    var flag = true;
    if (!checkInputBox($('#loginBox'), $('#errLogin'))) {
        flag = false;
    }
    if (!checkInputBox($('#passwordBox'), $('#errPassword'))) {
        flag = false;
    }
    return flag;
}

function checkInputBox(selector, errorTxt) {
    if (selector.val() == '') {
        selector.css({ 'background': 'url("/Resources/img/inputErr.png") no-repeat' });
        errorTxt.show();
        return false;
    }
    selector.css({ 'background': '' });
    errorTxt.hide();
    return true;
}

function successAuthorization(data) {
    $("#loginBtn").button('reset').css({ 'background': '' });
    if (data.Status == "error") {
        $('#servErrorTxt').text("Error. "+data.Message).show();
    }
    else if (data.Status == "server_error") {
        $('#servErrorTxt').text("Server error. Please try again later").show();
    }
    if (data.Status == "success") {
        $('#servErrorTxt').hide();
        var items = $.parseJSON(data.Message);
        $.cookie("userId", items.Id);
        $.cookie("userNS", items.NS);
        $.cookie("userS", items.Status);
        window.location.href = "Default.aspx?selectedItem=myGoals";
    }
}